import java.net.InetSocketAddress;

import java.util.Map;
import java.net.Proxy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.github.biezhi.elves.utils.BaiduApiUtils;
import io.github.biezhi.elves.utils.StringUtils;
import io.github.biezhi.elves.common.Constants;
import io.github.biezhi.elves.ok.http.FastHttpClient;

public class testBaiduApi {
	static final String imgData = "f:/hebing.png";
//	static final String imgData = "f:/clickCaptcha.png";
	static final String proxyIp = "132.122.1.4";
	static final int proxyPort = 9898;
	
	static final String APPID = "11165779";
	static final String APIKEY = "fdpUjEyZKi4lueH8rY4CsPG0";
	static final String SECRETKEY = "LFKEFdcPlmwBrbf2z2CPOCYvaLicOTF3";
	
	static String accessToken = "";
	
	static Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress(proxyIp, proxyPort));
	
	static final String baiduUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate";
	static final String accessTokenUrl = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=fdpUjEyZKi4lueH8rY4CsPG0&client_secret=LFKEFdcPlmwBrbf2z2CPOCYvaLicOTF3&";

	public static void main(String[] args) {
		try{
//			String result = BaiduApiUtils.getBaiduApiForAccurate(imgData);
//			System.out.println(result);
			
//			demoJson();
			
			BaiduApiUtils.getBaiduOcrLocation(imgData,"祸");
			
//			BaiDuOCRBean baiDuOCRBean = com.alibaba.fastjson.JSONObject.toJavaObject(JSON.parseObject(result), BaiDuOCRBean.class);
//			List<Words_result> list = baiDuOCRBean.getWords_result();
//			for (int i = 0; i < list.size(); i++) {
//				System.out.println(list.get(i).getWords());
//			}
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	private static void demoJson() {
		StringBuffer demoData = new StringBuffer();
		demoData.append("{")
			.append("\"log_id\": 2558404818365074204,")
			.append("\"direction\": 0,")
			.append("\"words_result_num\": 2,")
			.append("\"words_result\": [")
				.append("{")
					.append("\"words\": \"请点击图中的“归“字\",")
					.append("\"location\": {")
					.append("\"width\": 126,")
					.append("\"top\": 9,")
					.append("\"left\": 7,")
					.append("\"height\": 16")
				.append("},")
					.append("\"probability\": {")
					.append("\"variance\": 0.011608,")
					.append("\"average\": 0.951515,")
					.append("\"min\": 0.63775")
					.append("}")
				.append("},")
				.append("{")
						.append("\"words\": \"羽归\",")
						.append("\"location\": {")
						.append("\"width\": 125,")
						.append("\"top\": 49,")
						.append("\"left\": 70,")
						.append("\"height\": 30")
					.append("},")
					.append("\"probability\": {")
						.append("\"variance\": 0.0,")
						.append("\"average\": 0.998479,")
						.append("\"min\": 0.998111")
				.append("}")
			.append("}")
			.append("],")
			.append("\"language\": -1")
			.append("}");
		
		String demoJson = demoData.toString();
		System.out.println(demoJson);
		
		String jsonType = StringUtils.getJsonType(demoJson);
		if(Constants.JSON_STRING.equals(jsonType)) {
			JSONObject json = JSONObject.parseObject(demoJson);
			if(json.containsKey("words_result") && json.get("words_result")!=null){
				JSONArray array = json.getJSONArray("words_result");
				boolean existTarget = false;
				String targetWordString = "";
				for (int i = 0; i < array.size(); i++) {
					JSONObject jsonObject = array.getJSONObject(i);
					String wordString = jsonObject.getString("words");
					targetWordString = wordString.replace("请点击图中的“", "").replace("”字", "");
					if("请点击图中的“归”字".equals(wordString) || "请点击图中的“归“字".equals(wordString)) {
						existTarget = true;
						continue;
					}
					
					if(existTarget) {
						if(targetWordString.contains(wordString)) {
							JSONObject  locationJson = JSONObject.parseObject(jsonObject.getString("location"));
							Integer top = locationJson.getInteger("top");
							Integer left = locationJson.getInteger("left");
							
							System.out.println("top==>" + top + "，left===>" + left);
							break;
						}
					}
				}
			}
		}
	}

	/**
	 * 返回响应url内容
	 * @return
	 */
	private static String getHttpReponseBody(){
		String jsonStr = "";
		try {
			io.github.biezhi.elves.ok.http.Response okHttpResponse;
			okHttpResponse = FastHttpClient
					.newBuilder()
					.proxy(proxy)
					.build()
					.post()
					.addHeader("Content-Type", "application/x-www-form-urlencoded")
					.url(accessTokenUrl)
					.build()
					.execute();
			jsonStr = okHttpResponse.string();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonStr;
	}
	
	/**
	 * 返回响应url内容
	 * @return
	 */
	private static String getHttpReponseBody(String resquestUrl,Map<String, String> paramMap){
		String responseBody = "";
		try {
			String requestBody = JSON.toJSONString(paramMap);
			io.github.biezhi.elves.ok.http.Response okHttpResponse;
			okHttpResponse = FastHttpClient
					.newBuilder()
					.proxy(proxy)
					.build()
					.post()
					.addHeader("Content-Type", "application/x-www-form-urlencoded")
					.url(resquestUrl)
					.addParams("Body", requestBody)
					.build()
					.execute();
			responseBody = okHttpResponse.string();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return responseBody;
	}
	
	private static String getAccessToken() {
		String accessToken = "";
		String jsonStr = getHttpReponseBody();
		JSONObject json = JSONObject.parseObject(jsonStr);
		if(json.containsKey("access_token")) {
			accessToken = json.getString("access_token");
		}
		return accessToken;
	}
}